home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18391 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: ix.netcom.com!netnews
  2. From: giuliano@ix.netcom.com(Giuliano Carlini)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: String operator+ and memory leakage.
  5. Date: 19 Apr 1996 18:38:37 GMT
  6. Organization: Netcom
  7. Message-ID: <4l8mjd$flq@reader2.ix.netcom.com>
  8. References: <4l5fok$feo@utopia.hacktic.nl>
  9. NNTP-Posting-Host: lbx-ca7-26.ix.netcom.com
  10. X-NETCOM-Date: Fri Apr 19 11:38:37 AM PDT 1996
  11.  
  12. In <4l5fok$feo@utopia.hacktic.nl> Mike Tavares <MIKET@cdynamics.com>
  13. writes: 
  14. >
  15. >I have an implementation (not mine) of the String class that
  16. >is leaking memory during the + operator code.  The code follows:
  17. > <major snip>
  18. >String&
  19. >String::operator+( String& a_string )
  20. >    {
  21. >    int total_size = string_length + strlen( a_string ) + 1;
  22. >    char* temp_array = new char[total_size];
  23. >    char* char_array = a_string;
  24. >
  25. >    strcpy( temp_array, character_array );
  26. >    strcat( temp_array, char_array );
  27. >
  28. >    String* new_string = new String( temp_array );
  29. >    delete [] temp_array;
  30. >    return *new_string;
  31. >    }
  32. > <more snipping>
  33. >
  34. >My usage is:
  35. >
  36. >destString = string1 + string2 + string3...;
  37. >
  38. >
  39. >The problem is, when new_string is created and returned through a 
  40. >reference, no one ever deletes it.
  41.  
  42. DISCLOSURE: I license a 16 bit garbage collector to geodesic systems,
  43. and hope to earn royalies from its sale.
  44.  
  45. The solution - for me - is to use garbage collecter. The design is nice
  46. and general purpose. Changing it to avoid this problem will make
  47. String's less useful.
  48.  
  49. This is a perfect example of the real benefit of garbage collector's.
  50. They permit better designs, and of clearer code. Without them, you
  51. either have to mess up the class interface, or the client code.
  52.  
  53. You can find out more about garbage collector's for C++ at either:
  54.     http://www.geodesic.com - a commercial GC
  55.     ftp://parcftp.xerox.com/pub/gc - a freely available GC
  56.  
  57.  
  58. g
  59.